﻿using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using Cav;
using Cav.BaseClases;
using Nefela.CommonTypes;

namespace Nefela.BusinessLogic
{
    public partial class CustomerCardBL : BusinessLogicBase
    {
        public CustomerCardBL()
        {
            InitializeComponent();

            ModelCards = new CustomerCardsColection();
            cardsCustomers = Path.Combine(DomainContext.AppDataUserStorage, "customers.nefela");
        }

        public CustomerCardBL(IContainer container)
        {
            container.Add(this);

            InitializeComponent();

            ModelCards = new CustomerCardsColection();
            cardsCustomers = Path.Combine(DomainContext.AppDataUserStorage, "customers.nefela");
        }

        private String cardsCustomers;
        private SettingsBL setBL;

        public CustomerCardsColection ModelCards { get; private set; }
        public BindingList<FieldCardType> ModelFields { get; private set; }

        public void LoadCards()
        {
            ModelCards.Clear();

            setBL = new SettingsBL();
            setBL.LoadSetting();

            if (setBL.ModelPackegeDocs.CardCustomer.Count == 0 ||
                setBL.ModelPackegeDocs.TemplatesDocs.Count == 0)
                return;

            var cds = cardsCustomers.XMLDeserializeFromFile<CustomerCardsColection>();
            if (cds != null && cds.Count != 0)
                ModelCards.AddRange(cds);
            foreach (var card in ModelCards)
            {
                foreach (var fset in setBL.ModelPackegeDocs.CardCustomer)
                {
                    var fincard = card.Fields.FirstOrDefault(x => x.Name == fset.Name);
                    if (fincard == null)
                    {
                        fincard = new FieldCardType() { Name = fset.Name, FieldCardCustomer = fset };
                        card.Fields.Add(fincard);
                    }

                    fincard.FieldCardCustomer = fset;
                }

                var lostField = card.Fields.Where(x => x.FieldCardCustomer == null).ToArray();
                foreach (var item in lostField)
                    card.Fields.Remove(item);
            }
        }

        public void Save()
        {
            ModelCards.XMLSerialize(cardsCustomers);
        }

        public void RemoveCard(CustomerCardType card)
        {
            if (card == null)
                return;

            if (ModelCards.Contains(card))
                ModelCards.Remove(card);
        }
    }
}
